package com.xiaochong.bitong.api.service;

import com.alibaba.fastjson.JSON;
import com.google.gson.reflect.TypeToken;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.bitong.api.component.RedisCacheComponent;
import com.xiaochong.bitong.api.constant.ReturnCode;
import com.xiaochong.bitong.api.utils.ListSortPageUtil;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.common.data.mapper.SelfSelectedMapper;
import com.xiaochong.tir.common.data.mapperSearchResult.ExchangeTransactionpair;
import com.xiaochong.tir.common.data.po.*;
import com.xiaochong.tir.common.data.vo.ApiResultVo;
import com.xiaochong.tir.common.data.vo.BtUser;
import com.xiaochong.tir.common.data.vo.CurrencyQuotationResultVo;
import com.xiaochong.tir.common.util.RedisKeyApp;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;
import org.hibernate.engine.jdbc.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.*;

/**
 * @Description: 搜索
 * @Author: org
 * @CreateDate: 2018/8/13 19:52
 */
@Service
public class CoinAndPairSearchService {

    @Autowired
    private RedisServer redisServer;
    @Autowired
    private RedisCacheComponent redisCacheComponent;

    @Autowired
    private SelfSelectedMapper selfSelectedMapper;
    @Autowired
    private KActionDetailService kActionDetailService;
    @Autowired
    private CommonService commonService;
    /**
     *
     货币搜索
     * @param
     * @return List<T>
     */

    public ApiResultVo currencySea(Integer pageIndex, Integer pageSize, String searchText,String token) {
        ApiResultVo resultVo=new ApiResultVo();
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            List<CurrencyInfo> currencySeaVo = new ArrayList<>();//返回数据
            //判断参数是否正常
            if(StringUtils.isBlank(searchText)){//PARAMS_ERROR
                resultVo.setCode(ReturnCode.PARAMS_ERROR);
                resultVo.setMessage("参数错误");
                return resultVo;
            }
            if(pageIndex == null){
                pageIndex = 1;
            }
            if(pageSize == null){
                pageSize = 30;
            }
            //货币
            //List<CurrencyInfo> CurrencyInfoList= redisCacheComponent.getCurrencyList();
            List<CurrencyInfo> CurrencyInfoList= redisServer.getList(RedisKeyApp.SEARCH_COIN,new TypeToken<List<CurrencyInfo>>(){}.getType());
            //获取货币市值，用于排名
            Map<Integer,List<CurrencyInfo>> mapList = new HashMap<>();//存放搜索分类数据
            //Map<String,String> allData = new HashMap<>(); //存放搜索数据，用于去重
            List<Integer> keyList = new ArrayList<>();
            CurrencyInfo currencyInfo = new CurrencyInfo();
            String searchData;
            List<CurrencyInfo> list;//匹配第一
            String searchTextUp = searchText.toUpperCase();//转换成大写
            for(int i =0;i<CurrencyInfoList.size();i++){//按照简称匹配第一、第二、第三个位数，匹配全称，匹配中文
                currencyInfo = CurrencyInfoList.get(i);
                //currencyInfo.setIndustryCategoryIds(null);
                //currencyInfo.setCurrencyIndustryList(null);
                //currencyInfo.setCurrencyConceptList(null);
                String symbol = currencyInfo.getSymbol()!=null?currencyInfo.getSymbol().toUpperCase():"";
                String cmcId = currencyInfo.getCmcId()!=null?currencyInfo.getCmcId().toUpperCase():"";
                String coinName = currencyInfo.getCoinNameCn()!=null?currencyInfo.getCoinNameCn():"";
                boolean isExist = false;
                if(StringUtils.isNotBlank(symbol)){
                    int cuLength = symbol.length();
                    ////按照简称匹配第一、第二、第三个位数
                    for(int k =1;k<= cuLength;k++){
                        searchData = symbol.substring(k-1,cuLength);
                        if(searchData.startsWith(searchTextUp)){
                            list = mapList.get(k);
                            if(list == null){
                                list = new ArrayList<>();
                            }
                            //currencyInfo.setMarketCapCny(pullMardetPrice(currencyInfo.getCmcId()));
                            list.add(currencyInfo);
                            keyList.add(k);
                            mapList.put(k,list);
                            isExist = true;
                            break;
                        }
                    }
                    if(isExist){
                        continue;
                    }
                    //cumid全称
                    if(StringUtils.isNotBlank(cmcId)&&cmcId.equals(searchTextUp)){
                        list = mapList.get(999);
                        if(list == null){
                            list = new ArrayList<>();
                        }
                        //currencyInfo.setMarketCapCny(pullMardetPrice(currencyInfo.getCmcId()));
                        list.add(currencyInfo);
                        mapList.put(999,list);;
                        keyList.add(999);
                        isExist = true;
                    }
                    if(isExist){
                        continue;
                    }
                    //中文模糊
                    if(StringUtils.isNotBlank(coinName) && coinName.indexOf(searchText) >-1){
                        list = mapList.get(1000);
                        if(list == null){
                            list = new ArrayList<>();
                        }
                        //currencyInfo.setMarketCapCny(pullMardetPrice(currencyInfo.getCmcId()));
                        list.add(currencyInfo);
                        mapList.put(1000,list);;
                        keyList.add(1000);
                    }
                }
            }
            if(mapList.size() > 0){
                //分别排序,降序
               /* for(Map.Entry<Integer,List<CurrencyInfo>> mm : mapList.entrySet()){
                    list = mm.getValue();
                    Collections.sort(list, new Comparator<CurrencyInfo>() {
                        @Override
                        public int compare(CurrencyInfo o1, CurrencyInfo o2) {
                            if(o1.getMarketCapCny().doubleValue() > o2.getMarketCapCny().doubleValue()){
                                return -1;
                            }else if(o1.getMarketCapCny().doubleValue() == o2.getMarketCapCny().doubleValue()){
                                return 0;
                            }else{
                                return 1;
                            }
                        }
                    });
                }*/
                //放入list
                keyList = new ArrayList<>(new HashSet<>(keyList));
                Collections.sort(keyList);
                for(Integer key : keyList){
                    list = mapList.get(key);
                    currencySeaVo.addAll(list);
                }
                //返回分页xiang相应条数
                int total = currencySeaVo.size();
                int yu = total%pageSize;
                int pages = total/pageSize;
                if(yu > 0){
                    pages = pages+1;
                }
                currencySeaVo= ListSortPageUtil.pageBean(currencySeaVo,pageIndex,pageSize);
                //判断是否自选
                if(!StringUtils.isBlank(token)){
                    BtUser btUser = commonService.getUserByToken(token);
                    if(btUser != null && btUser.getId() != null){
                        Integer user_id = btUser.getId();
                        Map<String,Object> params = new HashMap<>();
                        params.put("user_id",user_id);
                        params.put("type",2);
                        List<Integer> uniqueAnnotationList = new ArrayList<>();
                        for(CurrencyInfo p : currencySeaVo){
                            uniqueAnnotationList.add(p.getId());
                        }
                        params.put("uniqueAnnotationList",uniqueAnnotationList);
                        List<SelfSelected> selectList = selfSelectedMapper.getSelfSelectByMideleId(params);
                        if(selectList != null && selectList.size() > 0){
                            Map<Integer,Integer>  map = new HashMap<>();
                            for(SelfSelected selected:selectList){
                                map.put(selected.getUniqueAnnotation(),selected.getUniqueAnnotation());
                            }
                            for(CurrencyInfo p : currencySeaVo){
                                if(map.containsKey(p.getId())){
                                    p.setSelfSelectFlag(1);
                                }
                            }
                        }
                    }
                }
                resultVo.setMessage("成功");
                resultVo.setCode(ReturnCode.SUCCESS);
                resultVo.setData(currencySeaVo);
                resultVo.setPages(pages);
                resultVo.setTotal(total);
            }else{
                resultVo.setPages(0);
                resultVo.setTotal(0);
                resultVo.setCode(ReturnCode.DATA_NOT_EXIST);
                resultVo.setMessage("无数据");
            }
            return resultVo;
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("货币搜索error",e);
            resultVo.setCode(ReturnCode.ERROR);
            resultVo.setMessage("系统错误");
            return  resultVo;
        }
    }

    /**
     * 热门货币
     * @return
     */
    public ApiResultVo currencyMarketSea() {
        ApiResultVo resultVo=new ApiResultVo();
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            List<CurrencyInfo> currencySeaVo = new ArrayList<>();//返回数据
            //货币
            List<CurrencyInfo> CurrencyInfoList= redisServer.getList(RedisKeyApp.SEARCH_COIN,new TypeToken<List<CurrencyInfo>>(){}.getType());
            if(CurrencyInfoList != null && CurrencyInfoList.size() > 0){
                int size = CurrencyInfoList.size()>6?6:CurrencyInfoList.size();
                for(int i=0;i<size;i++){
                    currencySeaVo.add(CurrencyInfoList.get(i));
                }
                resultVo.setMessage("成功");
                resultVo.setCode(ReturnCode.SUCCESS);
                resultVo.setData(currencySeaVo);
            }else{
                resultVo.setCode(ReturnCode.DATA_NOT_EXIST);
                resultVo.setMessage("无数据");
            }
            return resultVo;
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("热门货币error",e);
            resultVo.setCode(ReturnCode.ERROR);
            resultVo.setMessage("系统错误");
            return  resultVo;
        }
    }
    /**
     * 交易对搜索
     * @param pageIndex
     * @param pageSize
     * @param searchText
     * @return
     */
    public ApiResultVo pairSea(Integer pageIndex, Integer pageSize, String searchText,String token) {
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            //判断参数是否正常
            if(StringUtils.isBlank(searchText)){//PARAMS_ERROR
                resultVo.setCode(ReturnCode.PARAMS_ERROR);
                resultVo.setMessage("参数错误");
                return resultVo;
            }
            LogTrace.infoKvs("货币交易对搜索","pageIndex",String.valueOf(pageIndex),"pageSize",String.valueOf(pageSize),"searchText",searchText);
            if(pageIndex == null){
                pageIndex = 1;
            }
            if(pageSize == null){
                pageSize = 30;
            }
            List<ExchangeTransactionpair> resultList = new ArrayList<>();
            List<ExchangeTransactionpair> list = new ArrayList<>();
            Map<Integer,List<ExchangeTransactionpair>> mapList = new HashMap<>();//存放搜索分类数据
            List<Integer> keyList = new ArrayList<>();
            List<ExchangeTransactionpair> resultExchangeList = new ArrayList<>();
            List<ExchangeTransactionpair> middleList = redisServer.getList(RedisKeyApp.SEARCH_PAIR,new TypeToken<List<ExchangeTransactionpair>>(){}.getType());
            /*String redisDate = redisServer.get(RedisKeyApp.SEARCH_PAIR);
            List<ExchangeTransactionpair> middleList;
            if(StringUtils.isNotBlank(redisDate)){
                middleList = JSON.parseArray(redisDate,ExchangeTransactionpair.class);
            }else{
                middleList = new ArrayList<>();
            }*/
            //匹配交易对和交易所名称
            String searchData;
            String searchTextUp = searchText.toUpperCase();//转换成大写
            int searchLength = searchTextUp.length();
            if(middleList != null && middleList.size() > 0){
                for(ExchangeTransactionpair pair : middleList){
                    pair.setSelfSelectFlag(2);//默认非自选
                    String symbol = pair.getTransactionName()!=null?pair.getTransactionName():"";
                    String exchangeName = pair.getExchangeName()!=null?pair.getExchangeName().toUpperCase():"";
                    boolean isExist = false;
                    if(StringUtils.isNotBlank(symbol)) {
                        int cuLength = symbol.length();
                        ////按照简称匹配第一、第二、第三个位数
                        for (int k = 1; k <= cuLength; k++) {
                            searchData = symbol.substring(k - 1, cuLength);
                            if(searchData.length() < searchLength){//剩余位数小于当前查询长度跳出
                                break;
                            }
                            if (searchData.startsWith(searchTextUp)) {
                                //resultList.add(pair);
                                list = mapList.get(k);
                                if(list == null){
                                    list = new ArrayList<>();
                                }
                                list.add(pair);
                                keyList.add(k);
                                mapList.put(k,list);
                                isExist = true;
                                break;
                            }
                        }
                        if (isExist) {
                            continue;
                        }
                        //交易所全称
                        if (StringUtils.isNotBlank(exchangeName) && exchangeName.indexOf(searchTextUp) > -1) {
                            resultExchangeList.add(pair);
                        }
                    }
                }
            }
            keyList = new ArrayList<>(new HashSet<>(keyList));
            Collections.sort(keyList);
            for(Integer key : keyList){
                list = mapList.get(key);
                resultList.addAll(list);
            }
            resultList.addAll(resultExchangeList);
            //分页返回
            int total = resultList.size();
            int yu = total%pageSize;
            int pages = total/pageSize;
            if(yu > 0){
                pages = pages+1;
            }
            if(resultList.size() > 0){
                resultList= ListSortPageUtil.pageBean(resultList,pageIndex,pageSize);
                //判断当前交易对是否已经自选 getSelfSelectByMideleId
                if(!StringUtils.isBlank(token)){
                    BtUser btUser = commonService.getUserByToken(token);
                    if(btUser != null && btUser.getId() != null){
                        Integer user_id = btUser.getId();
                        Map<String,Object> params = new HashMap<>();
                        params.put("user_id",user_id);
                        params.put("type",1);
                        List<Integer> uniqueAnnotationList = new ArrayList<>();
                        for(ExchangeTransactionpair p : resultList){
                            uniqueAnnotationList.add(p.getMiddleId());
                        }
                        params.put("uniqueAnnotationList",uniqueAnnotationList);
                        List<SelfSelected> selectList = selfSelectedMapper.getSelfSelectByMideleId(params);
                        if(selectList != null && selectList.size() > 0){
                            Map<Integer,Integer>  map = new HashMap<>();
                            for(SelfSelected selected:selectList){
                                map.put(selected.getUniqueAnnotation(),selected.getUniqueAnnotation());
                            }
                            for(ExchangeTransactionpair p : resultList){
                                if(map.containsKey(p.getMiddleId())){
                                    p.setSelfSelectFlag(1);
                                }
                            }
                        }
                    }
                }
                resultVo.setMessage("成功");
                resultVo.setCode(ReturnCode.SUCCESS);
            }else{
                resultVo.setCode(ReturnCode.DATA_NOT_EXIST);
                resultVo.setMessage("无数据");
            }
            resultVo.setPages(pages);
            resultVo.setTotal(total);
            resultVo.setData(resultList);
            return  resultVo;
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("货币交易对搜索error",e);
            resultVo.setCode(ReturnCode.ERROR);
            resultVo.setMessage("系统错误");
            return  resultVo;
        }
    }


    /**
     * 拉取市值，排名使用
     * @param cmcId
     * @return
     */
   /* public Double pullMardetPrice(String cmcId){
        String redisCacheKey =  RedisKeysUtils.CURRENCY_MARKET+cmcId;
        String result=redisServer.get( redisCacheKey);
        if (result!=null){
            LogTrace.info("getCurrencyByCmcId" , "resultKeyRedis" , redisCacheKey );
            CurrencyQuotationResultVo currencyQuotationResultVo = JSON.parseObject( result,CurrencyQuotationResultVo.class );
            if(currencyQuotationResultVo!=null && currencyQuotationResultVo.getMarketCapCny()!=null){
                return currencyQuotationResultVo.getMarketCapCny();
            }
        }
        return 0D;
    }
*/

}
